<?php

/**
 * materia actions.
 *
 * @package    condorito
 * @subpackage materia
 * @author     Freddy Daniel Garcia
 */
class materiaActions extends sfActions {

  public function executeIndex(sfWebRequest $request) {
    $this->categorias = CondoritoCategoriaPeer::getConMaterias();
  }

  public function executeInscribir(sfWebRequest $request) {
    $materia = $this->getRoute()->getObject();
    foreach ($materia->selEstudiante($this->getUser()->getIdUsuario()) as $estudiante) {
      $ins = $materia->estaInscrita($estudiante->getId());
    }
    if ($ins == 0) {
      $materia->inscribir($this->getUser()->getIdUsuario());

      $this->getUser()
          ->setFlash('notice',
              sprintf('La materia %s ha sido inscrita exitosamente',
                  $materia->getNombre()));
    } else {
      $this->getUser()
          ->setFlash('error',
              sprintf('La materia %s ya la tiene inscrita!!!',
                  $materia->getNombre()));
    }

    $this->redirect($this->generateUrl('show_materia', $materia));
  }

  public function executeShow(sfWebRequest $request) {
    $this->materia = $this->getRoute()->getObject();
  }

  public function executeNew(sfWebRequest $request) {
    $this->form = new CondoritoMateriaForm();
  }

  public function executeCreate(sfWebRequest $request) {
    $this->form = new CondoritoMateriaForm();
    $this->processForm($request, $this->form);
    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request) {
    $this->form = new CondoritoMateriaForm($this->getRoute()->getObject());
  }

  public function executeUpdate(sfWebRequest $request) {
    $this->form = new CondoritoMateriaForm($this->getRoute()->getObject());
    $this->processForm($request, $this->form);
    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request) {
    $request->checkCSRFProtection();

    $materia = $this->getRoute()->getObject();
    $materia->delete();

    $this->redirect('materia/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form) {
    $form
        ->bind($request->getParameter($form->getName()),
            $request->getFiles($form->getName()));
    if ($form->isValid()) {
      $CondoritoMateria = $form->save();

      $this->redirect('materia/edit?id=' . $CondoritoMateria->getId());
    }
  }
}
